//
//  TaobaoProductView.swift
//  viewcontroller_test
//
//  Created by 曾思宇 on 16/4/4.
//  Copyright © 2016年 海南开工信息技术有限公司. All rights reserved.
//

import UIKit
import PageMenu

class TaobaoProductView: UIScrollView, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {

    var view_top: UITableView?
    var view_bottom: UIView?
    var view_Indicator: UILabel?
    
    var pageMenuViewController: UIViewController?
    
    
    var productPicturesTableViewCell: TableViewCellPictures?
    var productProfileTableViewCell: TableViewCellProfile?
    var storeProfileTableViewCell: TableViewCellStoreProfile?
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if newSuperview == nil {
            cleanup()
        }
        else {
            
            if !hasSetup {
                setupViews()
            }
        }
        
    }
    
    
    
    
    private var hasSetup = false
    
    func setupViews() {
        
        
        // 设置最顶部的 TableView
        view_top = UITableView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: 800), style: UITableViewStyle.Grouped)
        view_top?.autoresizingMask = .FlexibleWidth
        addSubview(view_top!)
        
        view_Indicator = UILabel(frame: CGRect(x: 0, y: 800, width: bounds.width, height: 40))
        view_Indicator?.text = "继续拖动，查看图文详情"
        view_Indicator?.font = UIFont.systemFontOfSize(11)
        view_Indicator?.textAlignment = .Center
        addSubview(view_Indicator!)
        
        
        // --------------------------------------------------------------------------------------------------------------
        // PageMenu 的设置
        //--------------------------------------------------------------------------------------------------------------
        var controllerArray : [UIViewController] = []
        let graphicDetailViewController = UIStoryboard(name: "TaobaoProductDetail", bundle: nil).instantiateViewControllerWithIdentifier("product_tuwen") as! GraphicDetailViewController
        graphicDetailViewController.title = "图文详情"
        graphicDetailViewController.refreshView.AddTarget(self, selector: #selector(TaobaoProductView.refresh(_:)))
        
        controllerArray.append(graphicDetailViewController)
        
        
        let controller = UIStoryboard(name: "TaobaoProductDetail", bundle: nil).instantiateViewControllerWithIdentifier("recommend")
        controller.title = "店家推荐"
        controllerArray.append(controller)
        
        

        let parameters: [CAPSPageMenuOption] = [
            .SelectedMenuItemLabelColor (UIColor(red: 255.0/255.0, green: 144.0/255.0, blue: 0.0, alpha: 1.0)),
            .UnselectedMenuItemLabelColor (UIColor.darkGrayColor()),
            .ScrollMenuBackgroundColor(UIColor(white: 1.0, alpha: 1.0)),
            .SelectionIndicatorColor(UIColor(red: 255.0/255.0, green: 144.0/255.0, blue: 0.0, alpha: 1.0)),
            .UseMenuLikeSegmentedControl(true),
            .MenuItemSeparatorPercentageHeight(0.1),
            .MenuItemWidthBasedOnTitleTextWidth (true)
        ]
        
        
        pageMenuViewController = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 0.0, frame.width, frame.height), pageMenuOptions: parameters)
        
        view_bottom = pageMenuViewController!.view
        addSubview(view_bottom!)
        
        
        view_top?.delegate = self
        view_top?.dataSource = self
        view_top?.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.New, context: nil)
        
        
        
        view_top?.registerNib(UINib(nibName: "TableViewCellPictures", bundle: nil), forCellReuseIdentifier: "pictures")
        productPicturesTableViewCell = view_top?.dequeueReusableCellWithIdentifier("pictures") as? TableViewCellPictures
        productPicturesTableViewCell?.imagesView.addImage(UIImage(named: "product_1")!)
        productPicturesTableViewCell?.imagesView.addImage(UIImage(named: "product_2")!)
        productPicturesTableViewCell?.imagesView.addImage(UIImage(named: "product_3")!)
        
        view_top?.registerNib(UINib(nibName: "TableViewCellProfile", bundle: nil), forCellReuseIdentifier: "profile")
        productProfileTableViewCell = view_top?.dequeueReusableCellWithIdentifier("profile") as? TableViewCellProfile
        
        view_top?.registerNib(UINib(nibName: "TableViewCellStoreProfile", bundle: nil), forCellReuseIdentifier: "store_profile")
        storeProfileTableViewCell = view_top?.dequeueReusableCellWithIdentifier("store_profile") as? TableViewCellStoreProfile
        
        view_top?.allowsSelection = false
        view_top?.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: 0.1))
        
        //contentSize = CGSize(width: bounds.width, height: 840)
        
        delegate = self
        
        hasSetup = true
    }
    
    func cleanup() {
        view_top?.removeObserver(self, forKeyPath: "contentSize")
    }
    
    
    
    
    
    // 监控显示宝贝详情的 TableView 的 ContentSiz的高度，以便扩大TableView的高度来容纳整个内容
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if keyPath == "contentSize" {
            
            
            view_top?.frame = CGRect(x: 0.0, y:0.0, width: bounds.width, height: (view_top?.contentSize.height)! + (view_top?.contentInset.top)! + (view_top?.contentInset.bottom)!)
            
            view_Indicator?.frame.origin = CGPoint(x: 0, y: view_top!.bounds.height)
            contentSize.height = (view_top?.bounds.height)!  + (view_Indicator?.bounds.height)!
            view_bottom?.frame.origin = CGPoint(x: 0, y: view_top!.bounds.height + view_Indicator!.bounds.height)
            
        }
    }
    
    // 图文详情的UIWebView和店家推荐的 UICollectionView用到的下拉刷新控件，触发后调用，用于回到宝贝详情的状态
    func refresh(sender: AnyObject) {
        
        if let refreshView = sender as? KGRefreshView {
            refreshView.endRefresh()
            
            restore()
        }
        
    }
    
    
    func restore() {
        
        UIView.animateWithDuration(0.3, animations: {
            self.contentSize.height = self.view_top!.bounds.height + self.view_Indicator!.bounds.height
        }){ _ in
            
            self.scrollEnabled = true
            
        }
    }
    
    
    var canTransition = false
    var transiting = false
    
    //
    // 计算 ScrollView 的滚动范围
    //
    func calcScrollRange() -> CGFloat {
        
        let delta = contentSize.height - (bounds.height - contentInset.top - contentInset.bottom)
        
        return max(0.0, delta)
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //NSLog("scrollView did scroll(contentOffset):\(scrollView.contentOffset)")
        
        let scrollRange = calcScrollRange()
        
        let delta = scrollView.contentOffset.y - scrollView.contentInset.top - scrollRange
        
        //NSLog("dragging:\(scrollView.dragging), tracking:\(scrollView.tracking), decelart:\(scrollView.decelerating)")
        
        if transiting {
            
            
            
        }
        else {
            
            
            if canTransition && scrollView.decelerating {
                
                beginTransition()
            }
                
                
            else if delta > 100.0 && !scrollView.decelerating {
                
                view_Indicator!.text = "释放拖动，查看图文详情"
                
                canTransition = true
                
                
            }
            else {
                view_Indicator?.text = "继续拖动，查看图文详情"
                canTransition = false
            }
        }
    }
    
    func beginTransition() {
        transiting = true
        
        scrollEnabled = false
        contentSize.height = view_top!.bounds.height + view_Indicator!.bounds.height + view_bottom!.bounds.height
        
        
        
        UIView.animateWithDuration(0.3, animations: {
            self.contentOffset.y = self.view_top!.bounds.height + self.view_Indicator!.bounds.height
        }) { (_) in
            self.endTransition()
        }
        
        
    }
    
    func endTransition() {
        
        transiting = false
        canTransition = false
    }

    
    
    /*========================================================================================================
     
     UITableView's delegate and datasource implementation
     
     ========================================================================================================*/
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            return 2
        }
        else if section == 1 {
            return 1
        }
        
        return 2
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 && indexPath.row == 0 {
            return productPicturesTableViewCell!
        }
        else if indexPath.section == 0 && indexPath.row == 1 {
            return productProfileTableViewCell!
        }
        else if indexPath.section == 1 && indexPath.row == 0 {
            return storeProfileTableViewCell!
        }
        
        return productPicturesTableViewCell!
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if indexPath.section == 0 && indexPath.row == 0 {
            let size = productPicturesTableViewCell?.sizeThatFits(CGSizeZero)
            return (size?.height)!
        }
        else if indexPath.section == 0 && indexPath.row == 1 {
            
            let size = productProfileTableViewCell?.sizeThatFits(CGSizeZero)
            
            return (size?.height)!
            
        }
        else if indexPath.section == 1 && indexPath.row == 0 {
            let size = storeProfileTableViewCell?.sizeThatFits(CGSizeZero)
            return (size?.height)!
        }
        
        
        
        return 45
        
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 4
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 1 {
            return 4
        }
        return 0
    }

}
